import { ExceptionFilter, Catch, ArgumentsHost, Logger } from '@nestjs/common';
import { HttpException } from '@nestjs/common';
import * as path from 'path';
import { CommonConfig, Utils } from '../index';
const STATIC_PAGE_LIST = CommonConfig.STATIC_PAGE_LIST;
@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse();
    const request = ctx.getRequest();
    const status = exception.getStatus();
    // 检查是否地址栏URL请求
    if (Utils.Url.checkUrlRule(STATIC_PAGE_LIST, request.url)) {
      response.sendFile(
        path.join(__dirname, '../../../', CommonConfig.STATIC_PATH),
      );
      return;
    }
    // console.log('http exception:', exception)
    const exceptions = exception.getResponse();
    console.log('http exception:', typeof exceptions, exceptions);
    // console.log(exceptions[0].constraints)
    let code: number = exceptions['code'] || 3001;
    let message = exceptions['message'];
    console.log('http exception message:', message);
    if (message instanceof Array && message.length > 0) {
      let oriMessage: any = null;
      if (message[0].constraints.hasOwnProperty('isInt')) {
        oriMessage = message[0].constraints.isInt;
      } else if (message[0].constraints.hasOwnProperty('IsArray')) {
        oriMessage = message[0].constraints.IsArray;
      } else if (message[0].constraints.hasOwnProperty('isEmail')) {
        oriMessage = message[0].constraints.isEmail;
      } else if (message[0].constraints.hasOwnProperty('isString')) {
        oriMessage = message[0].constraints.isString;
      } else if (message[0].constraints.hasOwnProperty('IsDate')) {
        oriMessage = message[0].constraints.IsDate;
      } else if (message[0].constraints.hasOwnProperty('IsBoolean')) {
        oriMessage = message[0].constraints.IsBoolean;
      } else if (message[0].constraints.hasOwnProperty('isLength')) {
        oriMessage = message[0].constraints.isLength;
      } else if (message[0].constraints.hasOwnProperty('isNumber')) {
        oriMessage = message[0].constraints.isNumber;
      } else if (message[0].constraints.hasOwnProperty('min')) {
        oriMessage = message[0].constraints.min;
      } else if (message[0].constraints.hasOwnProperty('max')) {
        oriMessage = message[0].constraints.max;
      }
      if (oriMessage.includes('message')) {
        message = JSON.parse(oriMessage).message;
        code = JSON.parse(oriMessage).code;
      } else {
        message = oriMessage;
      }
    }

    const result = {
      code,
      message,
      data: null,
    };
    Logger.log(`result:${JSON.stringify(result)}`);
    response.status(status).json(result);
  }
}
